﻿using System.Collections.Generic;
using System.IO;

namespace LegSec.NugetThirdPartyLicenseFileGenerator
{
    public class LicenseFileGenerator
    {
        public string GeneratedFileLocation { get; set; }
        public string GeneratedFileName { get; set; }
        public string RootDirectory { get; set; }
        public string NuspecFilesDirectoryPath { get; set; }
        public string IgnoredNameSpace { get; set; }

        public LicenseFileGenerator(string rootDirectory, string generatedFileLocation, string generatedFileName, string ignoredNameSpace)
        {
            GeneratedFileName = generatedFileName;
            RootDirectory = rootDirectory;
            GeneratedFileLocation = generatedFileLocation;
            IgnoredNameSpace = ignoredNameSpace;
            NuspecFilesDirectoryPath = Path.Combine(RootDirectory, "nuspec");
        }

        public void Generate()
        {
            var nupkgSelector = new NupkgSelector();
            var nupkgFiles = nupkgSelector.findNupkgFromDirectory(new DirectoryInfo(RootDirectory));
            var nuspecDirectory = new DirectoryInfo(NuspecFilesDirectoryPath);
            nuspecDirectory.Create();
            NupkgReader.ExtractNspecFilesToDirectory(nupkgFiles, NuspecFilesDirectoryPath);
            List<PackageLicenseInformation> licenseInformation = new List<PackageLicenseInformation>();
            foreach (var fileInfo in nuspecDirectory.GetFiles())
            {
                var fileReader = new NuspecReader(fileInfo);
                licenseInformation.Add(fileReader.GetLicenceInformationFromNuspecFile());
            }
            ILicenseInformationWriter licenseFileWriter = new XmlLicenseWriter(Path.Combine(GeneratedFileLocation, GeneratedFileName), IgnoredNameSpace);
            licenseFileWriter.WriteLicences(licenseInformation);            
            nuspecDirectory.Delete(true);
        }
    }
}
